package com.zp.business.impl.bedRec;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.api.RemoteClinicItemDictService;
import com.zp.base.api.bo.ClinicItemDictBo;
import com.zp.base.api.vo.ClinicItemDictVo;
import com.zp.business.entity.bedRec.BedRec;
import com.zp.business.entity.bedRec.bo.BedRecBo;
import com.zp.business.entity.bedRec.vo.BedRecVo;
import com.zp.business.mapper.bedRec.BedRecMapper;
import com.zp.business.service.bedRec.IBedRecService;
import com.zp.common.core.constant.CacheNames;
import com.zp.common.core.constant.UserConstants;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.redis.utils.CacheUtils;
import com.zp.system.api.RemoteDeptService;
import com.zp.system.api.entity.SysDept;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 床位Service业务层处理
 *
 * @author zhang peng
 * @ date 2024-06-25
 */
@RequiredArgsConstructor
@Service
public class BedRecServiceImpl implements IBedRecService {

    static Map<String, SysDept> SYS_DEPT_MAP = CacheUtils.get(CacheNames.SYS_DEPT);
    private final BedRecMapper baseMapper;
    @DubboReference
    private RemoteClinicItemDictService remoteClinicItemDictService;
    @DubboReference
    private RemoteDeptService remoteDeptService;


    /**
     * 查询床位
     */
    @Override
    public BedRecVo queryById(String bedId) {
        BedRecVo bedRecVo = baseMapper.selectVoById(bedId);
        List<ClinicItemDictVo> clinicItemDictList = selectClinicItemDictList(bedRecVo.getOrgId());
        bedRecVo.setWordCodeName(ObjectUtils.isNotEmpty(SYS_DEPT_MAP) && StringUtils.isNotBlank(bedRecVo.getWordCode()) ?
                SYS_DEPT_MAP.get(bedRecVo.getWordCode()).getDeptName() : "");
        if (CollectionUtils.isNotEmpty(clinicItemDictList)) {
            List<ClinicItemDictVo> collect = clinicItemDictList.stream()
                    .filter(itemDict -> StringUtils.equals(bedRecVo.getBedGrade(), itemDict.getClinicItemId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                bedRecVo.setBedGradeName(collect.get(0).getItemName());
            }
        }
        return bedRecVo;
    }

    /**
     * 查询床位列表(分页)
     */
    @Override
    public TableDataInfo<BedRecVo> queryPageList(BedRecBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BedRec> lqw = buildQueryWrapper(bo);
        if (StringUtils.isNotBlank(bo.getBedBlank())) {
            if (StringUtils.equals(bo.getBedBlank(), UserConstants.YES)) {
                // 床位占用
                lqw.isNotNull(BedRec::getVisitId).apply("visit_id != ''");
            } else {
                // 床位未占用
                lqw.isNull(BedRec::getVisitId)
                        .or().eq(BedRec::getVisitId, "");
            }
        }
        List<ClinicItemDictVo> clinicItemDictList = selectClinicItemDictList(bo.getOrgId());
        Page<BedRecVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(item -> {
            item.setWordCodeName(ObjectUtils.isNotEmpty(SYS_DEPT_MAP) && StringUtils.isNotBlank(item.getWordCode()) ?
                    SYS_DEPT_MAP.get(item.getWordCode()).getDeptName() : "");
            if (CollectionUtils.isNotEmpty(clinicItemDictList)) {
                List<ClinicItemDictVo> collect = clinicItemDictList.stream()
                        .filter(itemDict -> StringUtils.equals(item.getBedGrade(), itemDict.getClinicItemId())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect)) {
                    item.setBedGradeName(collect.get(0).getItemName());
                }
            }
        });
        return TableDataInfo.build(result);
    }

    public List<ClinicItemDictVo> selectClinicItemDictList(String orgId) {
        ClinicItemDictBo clinicItemDictBo = new ClinicItemDictBo();
        clinicItemDictBo.setOrgId(orgId);
        return remoteClinicItemDictService.queryList(clinicItemDictBo);
    }

    /**
     * 查询床位列表(不分页)
     */
    @Override
    public List<BedRecVo> queryList(BedRecBo bo) {
        LambdaQueryWrapper<BedRec> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BedRec> buildQueryWrapper(BedRecBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BedRec> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBedId()), BedRec::getBedId, bo.getBedId());
        lqw.eq(StringUtils.isNotBlank(bo.getPatientId()), BedRec::getPatientId, bo.getPatientId());
        lqw.eq(StringUtils.isNotBlank(bo.getVisitId()), BedRec::getVisitId, bo.getVisitId());
        lqw.eq(StringUtils.isNotBlank(bo.getWordCode()), BedRec::getWordCode, bo.getWordCode());
        lqw.eq(bo.getBedNo() != null, BedRec::getBedNo, bo.getBedNo());
        lqw.eq(StringUtils.isNotBlank(bo.getBedLabel()), BedRec::getBedLabel, bo.getBedLabel());
        lqw.eq(StringUtils.isNotBlank(bo.getRoomNo()), BedRec::getRoomNo, bo.getRoomNo());
        lqw.eq(StringUtils.isNotBlank(bo.getDeptId()), BedRec::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getBedApprovedType()), BedRec::getBedApprovedType, bo.getBedApprovedType());
        lqw.eq(StringUtils.isNotBlank(bo.getBedSexType()), BedRec::getBedSexType, bo.getBedSexType());
        lqw.eq(StringUtils.isNotBlank(bo.getBedGrade()), BedRec::getBedGrade, bo.getBedGrade());
        lqw.eq(StringUtils.isNotBlank(bo.getBedStatus()), BedRec::getBedStatus, bo.getBedStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getLockStatus()), BedRec::getLockStatus, bo.getLockStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getLockOperator()), BedRec::getLockOperator, bo.getLockOperator());
        lqw.eq(StringUtils.isNotBlank(bo.getBedOccupy()), BedRec::getBedOccupy, bo.getBedOccupy());
        lqw.eq(StringUtils.isNotBlank(bo.getAirconditionClass()), BedRec::getAirconditionClass, bo.getAirconditionClass());
        lqw.eq(bo.getLastAcctDateTim() != null, BedRec::getLastAcctDateTim, bo.getLastAcctDateTim());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), BedRec::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), BedRec::getRemarks, bo.getRemarks());
        return lqw;
    }

    /**
     * 新增床位
     */
    @Override
    public Boolean insertByBo(BedRecBo bo) {
        BedRec add = BeanUtil.toBean(bo, BedRec.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setBedId(add.getBedId());
        }
        return flag;
    }

    /**
     * 修改床位
     */
    @Override
    public Boolean updateByBo(BedRecBo bo) {
        BedRec update = BeanUtil.toBean(bo, BedRec.class);
        update.updateInfo();
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BedRec entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除床位
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 获取护理单元床位对照
     *
     * @param wordCode
     * @return
     */
    @Override
    public List<BedRecVo> getDeptVsBedList(String wordCode, String orgId) {
//        SysDept sysDept = new SysDept();
//        sysDept.setOrgId(orgId);
//        List<SysDept> sysDeptList = remoteDeptService.selectDeptList(sysDept);
        BedRecBo bo = new BedRecBo();
        bo.setOrgId(orgId);
        List<BedRecVo> deptVsBedList = baseMapper.getDeptVsBedList(bo);
        deptVsBedList.forEach(item->{
            item.setWordCodeName(ObjectUtils.isNotEmpty(SYS_DEPT_MAP) && StringUtils.isNotBlank(item.getWordCode()) ?
                    SYS_DEPT_MAP.get(item.getWordCode()).getDeptName() : "");
        });
        return deptVsBedList;
    }
}
